/*
 * @Author: your name
 * @Date: 2021-05-18 13:35:04
 * @LastEditTime: 2021-07-15 09:42:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \MF-IPFS-sales\.rnext\library\components\exportModal\ExportModal.tsx
 */
import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Input, InputNumber, Modal, Select } from 'antd';
import { Formx } from '@library';
import moment from 'moment';
import { message } from '@library/utils';

const t = (window as any).$app?.t;
const { Option } = Select;

const formItems = [
  { label: t('fileName'), name: 'tableName' },
  { label: t('fileType'), name: 'fileType' },
  { label: t('exportDataType'), name: 'exportDataType' },
  { label: t('maxExportLines'), name: 'maxExportLines' },
];

const _ExportExcel = (props: any, ref: any) => {
  const [isVisible, setIsVisible] = useState(false);
  const [moduleName, setModuleName] = useState('');
  const [query, setQuery] = useState({});
  const [initialValues, setInitialValues] = useState({
    tableName: `order${moment(new Date()).format('YYYYMMDD')}`,
    fileType: 'Excel',
    exportDataType: 'all',
    maxExportLines: 3000,
  });
  const formRef = useRef<any>();

  const extra = useMemo(() => {
    return [
      {
        name: 'tableName',
        render: (record: any) => <Input value={initialValues.tableName} />,
      },
      {
        name: 'fileType',
        render: (record: any) => (
          <Select value={initialValues.fileType}>
            <Option value="Excel">xlsx</Option>
            <Option value="Csv">csv</Option>
          </Select>
        ),
      },
      {
        name: 'exportDataType',
        render: (record: any) => (
          <Select value={initialValues.exportDataType}>
            <Option value="all">{t('allData')}</Option>
            <Option value="part">{t('partData')}</Option>
          </Select>
        ),
      },
      {
        name: 'maxExportLines',
        render: (record: any) => (
          <InputNumber value={initialValues.maxExportLines} min={1} max={50000} />
        ),
      },
    ];
  }, [initialValues]);

  const handleOk = async () => {
    const data = await formRef.current.validateFields();

    if (!data.tableName) data.tableName = `order${moment(new Date()).format('YYYYMMDD')}`;

    let queryObj: any = { ...query, tableName: data.tableName };

    if (data.exportDataType === 'part') {
      queryObj = { ...queryObj, ...props.query }
    }

    queryObj.pages = {};
    queryObj.pages.pageSize = data.maxExportLines;
    queryObj.pages.page = 1;
    
    queryObj = props.handleQuery?.(queryObj, data) || queryObj;
    window.open(`/bk/export${data.fileType}/${moduleName}?encodeURIComponent=1&args=${encodeURIComponent(JSON.stringify(queryObj))}`, '_blank');

    setIsVisible(false);
  };

  const handleCancel = useCallback(() => setIsVisible(false), []);

  useImperativeHandle(ref, () => ({
    hide: () => setIsVisible(false),
    show: (v: any) => {
      if (!v) return message.error('请填写导出配置项')
      if (!v.moduleName) return message.error('请填写导出moduleName')
      setInitialValues(v?.initialValues || {})
      setModuleName(v?.moduleName || '')
      setQuery(v?.query || {})
      setIsVisible(true)
    },
  }));

  return (
    <Modal visible={isVisible} title={t('exportExcel')} onOk={handleOk} onCancel={handleCancel} destroyOnClose>
      <Formx initialValues={initialValues} formItems={formItems} groupNumber={1} extra={extra} ref={formRef}></Formx>
    </Modal>
  );
};

export default forwardRef(_ExportExcel);
